package com.controller.backend;

import com.biz.HotelPhotoBiz;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.model.HotelPhoto;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by jc on 2019/11/26.
 */
@Controller
@RequestMapping("/backend/security/hotelPhoto")
public class HotelPhotoController extends BaseController<HotelPhoto> {
    @Autowired
    private HotelPhotoBiz hotelPhotoBiz;

    @RequestMapping(value = "/updateSynthesisImg")
    @ResponseBody
    public Result upload(MultipartFile file, HttpServletRequest request) {
        try {
            String path = request.getSession().getServletContext().getRealPath("/");
            path = path + "/" + "static" + "/" + "data" + "/" + "images" + "/";
            String image = uploadImage(file, path);
            return ResultGenerator.genSuccessResult(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("上传失败");
    }

    public static String uploadImage(MultipartFile file, String path) throws IOException {
        String name = file.getOriginalFilename();
        String suffixName = name.substring(name.lastIndexOf("."));
        Date date = new Date();
        String hash = String.valueOf(date.getTime());//给照片自定义一个名字，用时间做名称，不会重复
        String fileName = hash + suffixName;
        File tempFile = new File(path, fileName);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        tempFile.createNewFile();
        file.transferTo(tempFile);
        return tempFile.getName();
    }
}
